/*
 * CheckLogin.java
 * 
 * Version information
 * 
 * Mar 16, 2006
 * 
 * Copyright (c) AmSoft Systems, 2006
 */
package net.amsoft.iservice.icontact.webapp.struts.action;

import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.amsoft.iservice.icontact.hibernate.dataObject.LoginData;
import net.amsoft.iservice.icontact.service.IContact;
import net.amsoft.iservice.util.IServiceUtil;
import net.amsoft.iservice.util.ResolverClient;
import static net.amsoft.iservice.icontact.util.IContactConstants.*;
import static net.amsoft.iservice.util.IServiceConstants.PARAM_SERVICE_ACTIVE;
import static net.amsoft.iservice.util.IServiceConstants.RESPONSE_URI;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * This Action class is used to check if user is logged in or not, if it is then
 * takes <BR>
 * him to his homepage otherwise ask the iname to login.
 * 
 * @author rahul
 * @author mohit
 */
public class CheckLogin extends BaseAction {
    private static final Logger oLogger = Logger.getLogger(CheckLogin.class);

    public ActionForward process(ActionMapping oMapping, ActionForm oForm,
            HttpServletRequest oRequest, HttpServletResponse oResponse)
            throws Exception {
        oLogger.info("process() : entry");
        /*
         * Check if request is for contact page
         */
        String sXri = oRequest.getParameter(REQ_PTR_SYN);
        if (sXri != null) {
            sXri = sXri.replaceAll("\\s", "+");
            String sIname = null;
            try {
                sIname = IServiceUtil.getIName(sXri);
                if (sIname == null)
                    throw new Exception("Invalid XRI");
                else
                    sIname = sIname.toLowerCase();
            } catch (Exception e) {
                oLogger.warn("process(): invalid xri:" + sXri);
            }

            /*
             * CHECK IF THE SERVICE IS ACTIVE OR NOT for the given synonym and
             * respond
             */
            String sAcceptHeader = oRequest.getParameter(PARAM_SERVICE_ACTIVE);
            if (sAcceptHeader != null && sAcceptHeader.equals("true")) {

                String sGINU = ResolverClient.getGlobalINumber(sIname);
                boolean bIsSubscribed = IContact.isSynonymSubscribed(sXri,
                        sGINU, oRequest.getServerName());
                if (bIsSubscribed) {
                    oResponse.setStatus(HttpServletResponse.SC_OK); // HTTP 200
                    // OK
                    // Write response back to client
                    oResponse.setContentType(RESPONSE_URI);
                    PrintWriter out = oResponse.getWriter();
                    out.println("http://" + oRequest.getServerName()
                            + "/icontact/Login?synonym=" + sIname);
                    out.flush();
                    out.close();
                } else {
                    oResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); // HTTP
                                                                            // 404
                }

                return new ActionForward();
            }

            /*
             * Redirect to Contact page
             */
            sXri = URLEncoder.encode(sXri, "UTF-8");
            ActionForward oActionForward = new ActionForward("/Contact?"
                    + REQ_PTR_SYN + "=" + sIname, true);
            return oActionForward;
        }

        LoginData oLoginData = (LoginData) oRequest.getSession(false)
                .getAttribute(SESSION_LOGIN_OBJ);

        if (oLoginData.isLoginStatus()) {
            try {
                if (oLoginData.getAllSynonyms().size() == 0) {
                    // FIXME is this required??
                    IContact.loadSynonyms(oLoginData);
                }
            } catch (Exception e) {
                oLogger.error("process() : Exception : " + e.getMessage()
                        + ", Login Status: true");
            }
            oLogger.info("process() : Forward to welcome page");
            return oMapping.findForward(FWD_SUCCESS);
        } else {
            oLogger.info("process() : Forward to iname page");
            return oMapping.findForward(FWD_FAILURE);
        }
    }
}
